<?php

namespace Frontend;

/**
 * Description of LyricsController
 *
 * @author dung
 */
use BaseController;
use Config;
use Input;
use Lang;
use MyModel;
use Exception;
use Redirect;
use Sentry;
use Str;
use Validator;
use View;
use Tone;
use Lyric;
use GuitarTabs;
use Jinput;
use Video;
use Lesson;
use Topic;
use DB;
use Request;
use Response;

class LyricsController extends BaseController
{

    public function __construct()
    {
        parent::__construct();
        $this->beforeFilter('auth', array('only' => 'getCreate', 'postCreate', 'postAddVersion'));
    }

    public function getIndex()
    {

        $myModel = new \MyModel();

        $publishCondition = array('field' => 'lyrics.status', 'opr' => '=', 'value' => 'published');
        $data['appends']['ch'] = Jinput::get('ch');
        $data['appends']['key'] = Jinput::get('key');
        $data['appends']['tone'] = Jinput::get('tone', '');
        $data['appends']['order'] = Jinput::get('order', 'id');
        $data['appends']['singer_id'] = Jinput::get('singer', '');
        $data['appends']['musician_id'] = Jinput::get('musician', '');

        $arrParams = array();
        if ($data['appends']['ch'] != '') {
            if ($data['appends']['ch'] == '0..9')
                $arrParams['conditions'][] = array('field' => 'lyrics.title', 'opr' => 'RLIKE', 'value' => '^[0-9]');
            else
                $arrParams['conditions'][] = array('field' => 'lyrics.title', 'opr' => 'LIKE', 'value' => $data['appends']['ch'] . '%');
        }
        if ($data['appends']['key']) {
            $arrParams['conditions'][] = array('field' => 'lyrics.title', 'opr' => 'LIKE', 'value' => '%' . $data['appends']['key'] . '%');
        }
        if ($data['appends']['tone'] != '') {
            $arrParams['conditions'][] = array('field' => 'lyrics.tone_id', 'opr' => '=', 'value' => $data['appends']['tone']);
        }

        if ($data['appends']['singer_id'] != '')
            $arrParams['conditions'][] = array('field' => 'lyrics.singer_id', 'opr' => '=', 'value' => $data['appends']['singer_id']);
        if ($data['appends']['musician_id'] != '')
            $arrParams['conditions'][] = array('field' => 'lyrics.musician_id', 'opr' => '=', 'value' => $data['appends']['musician_id']);
        $arrParams['conditions'][] = $publishCondition;
        $arrParams['left_joins'][] = array('table' => 'tones', 'pk' => 'tones.id', 'fk' => 'lyrics.tone_id');
        $arrParams['left_joins'][] = array('table' => 'singers as s1', 'pk' => 's1.id', 'fk' => 'lyrics.singer_id');
        $arrParams['left_joins'][] = array('table' => 'singers as m1', 'pk' => 'm1.id', 'fk' => 'lyrics.musician_id');
        $arrParams['selects'] = array('lyrics.*', 's1.name as singer_name', 'm1.name as musician_name', 'tones.title as tone_title');
        $arrParams['orders'] = array('field' => $data['appends']['order'], 'type' => 'DESC');
        $arrParams['paginate']['nums'] = 25;
        $arrParams['paginate']['appends'] = $data['appends'];
        $data['lyrics'] = $myModel->listItems('Lyric', $arrParams);

        //
        $data['lyric_most_views'] = $myModel->listTop('Lyric', array('top' => 'views', 'take' => 10, 'conditions' => array($publishCondition)));
        //
        $data['lyric_most_focus'] = $myModel->listTop('Lyric', array('top' => 'is_hot', 'take' => 10, 'conditions' => array($publishCondition)));

        //
        $data['lyric_most_thanks'] = $myModel->listTop('Lyric', array('top' => 'thanks', 'take' => 10, 'conditions' => array($publishCondition)));

        //
        $data['lyric_most_favourites'] = $myModel->listTop('Lyric', array('top' => 'favourites', 'take' => 10, 'conditions' => array($publishCondition)));

        return View::make('frontend/lyrics/index', compact('data'));

    }

//    public function getDetail($id, $slug)
//    {
//        $mode = Input::get('mode', '');
//
//        if ($mode != 'fullscreen') {
//            // get lyric
//            $data['lyric'] = Lyric::join('users', 'users.id', '=', 'lyrics.user_id')
//                ->leftJoin('singers as s1', 's1.id', '=', 'lyrics.singer_id')
//                ->leftJoin('singers as m1', 'm1.id', '=', 'lyrics.musician_id')
//                ->leftJoin('tones', 'tones.id', '=', 'lyrics.tone_id')
//                ->where('lyrics.id', '=', $id)->where('lyrics.status', '=', 'published')
//                ->select('lyrics.*', 'users.username', 'users.avatar', 's1.name as singer_name', 'm1.name as musician_name', 'tones.title as tone_title')
//                ->first();
//            // check if lyric exists
//            if (is_null($data['lyric']))
//                return \App::abort(404);
//            // processing lyric
//            $data['guitar_tab'] = new GuitarTabs();
//            $data['guitar_tab']->add_section('', $data['lyric']->content);
//            // lyric same singer
//            $data['same_singer'] = Lyric::where('lyrics.status', '=', 'published')
//                ->where('singer_id', '=', $data['lyric']->singer_id)
//                ->take(5)->select('lyrics.*')
//                ->get();
//            $data['topics'] = $data['lyric']->topics()->get();
//            // video same name
//            $lyricName = explode('-', $data['lyric']->title);
//
//            $data['videos'] = Video::where('videos.status', '=', 'published')
//                ->where(function ($where) use ($lyricName) {
//                    $i = 0;
//                    foreach ($lyricName as $lName) {
//                        if ($i == 0)
//                            $where->where('videos.title', 'LIKE', '%' . trim($lName) . '%');
//                        else
//                            $where->orWhere('videos.title', 'LIKE', '%' . trim($lName) . '%');
//                    }
//                })->take(5)->orderBy('videos.id', 'DESC')->get();
//            // lesson same tone
//            $data['lesson_same_tone'] = Lesson::join('users', 'users.id', '=', 'lessons.user_id')
//                ->where('lessons.tone_id', '=', $data['lyric']->tone_id)
//                ->select('lessons.*', 'users.username')->where('lessons.status', '=', 'published')
//                ->take(8)->orderBy('lessons.id', 'DESC')->get();
//            $data['thanked'] = $data['favourited'] = 'login';
//            if (Sentry::check()) {
//                $uId = $this->data['u']->id;
//                $data['thanked'] = $data['lyric']->thanks()->where('user_id', '=', $uId)->count() > 0 ? 'thank_active' : 'thank';
//                $data['favourited'] = $data['lyric']->favourites()->where('user_id', '=', $uId)->count() > 0 ? 'favourite_active' : 'favourite';
//            }
//
//            // other version
//            $parent_id = $data['lyric']->parent_id != 0 ? $data['lyric']->parent_id : $data['lyric']->id;
//            $data['versions'] = Lyric::join('users', 'users.id', '=', 'lyrics.user_id')
//                ->where('status', '=', 'published')->where('lyrics.id', '!=', $id)
//                ->where(function ($where) use ($parent_id) {
//                    $where->where('lyrics.parent_id', '=', $parent_id)
//                        ->orWhere('lyrics.id', '=', $parent_id);
//                })
//                ->select('lyrics.*', 'username')->get();
//
//            //main lyric
//            if ($data['lyric']->parent_id != 0)
//                $data['main_lyric'] = Lyric::find($parent_id);
//            //
//
//
//            return View::make('frontend/lyrics/details', compact('data'));
//        } else {
//            $data['lyric'] = Lyric::join('users', 'users.id', '=', 'lyrics.user_id')
//                ->where('lyrics.status', '=', 'published')->where('lyrics.id', '=', $id)
//                ->select('lyrics.*', 'username')->first();
//            if (is_null($data['lyric']))
//                \App::abort(404);
//
//            $data['guitar_tab'] = new GuitarTabs();
//            $data['guitar_tab']->add_section('', $data['lyric']->content);
//
//            return View::make('frontend/lyrics/details-fullscreen', compact('data'));
//        }
//    }
    public function getDetail($id, $slug)
    {
        $mode = Input::get('mode', '');
        // get lyric
        $data['lyric'] = Lyric::join('users', 'users.id', '=', 'lyrics.user_id')
            ->where('lyrics.id', '=', $id)->where('lyrics.status', '=', 'published')
            ->select('lyrics.*', 'users.username', 'users.avatar')
            ->first();
        if (is_null($data['lyric']))
            \App::abort(404);

        // processing lyric
        $data['guitar_tab'] = new GuitarTabs();
        $data['guitar_tab']->add_section('', $data['lyric']->content);

        if ($mode != 'fullscreen') {
            // main lyric
            $parent_id = $data['lyric']->parent_id != 0 ? $data['lyric']->parent_id : $data['lyric']->id;
            // get main lyric
            $data['main_lyric'] = Lyric::leftJoin('singers as s', 's.id', '=', 'lyrics.singer_id')
                ->leftJoin('singers as m', 'm.id', '=', 'lyrics.musician_id')
                ->select('lyrics.*', 's.name as singer_name', 'm.name as musician_name')
                ->where('lyrics.id', '=', $parent_id)
                ->groupBy('lyrics.id')->first();

            // get topics
            $data['topics'] = $data['main_lyric']->topics()->get();
            // get lyric name
            $lyricName = explode('-', $data['lyric']->title);
            // get videos same name
            $data['videos'] = Video::where('videos.status', '=', 'published')
                ->where(function ($where) use ($lyricName) {
                    $i = 0;
                    foreach ($lyricName as $lName) {
                        if ($i == 0)
                            $where->where('videos.title', 'LIKE', '%' . trim($lName) . '%');
                        else
                            $where->orWhere('videos.title', 'LIKE', '%' . trim($lName) . '%');
                        $i++;
                    }
                })->take(5)->orderBy('videos.id', 'DESC')->get();
            // lyric same singer

            $data['same_singer'] = Lyric::where('lyrics.status', '=', 'published')
                ->where('singer_id', '=', $data['main_lyric']->singer_id)
                ->take(5)->select('lyrics.*')
                ->get();
            // get lesson same tone
            $data['lesson_same_tone'] = Lesson::join('users', 'users.id', '=', 'lessons.user_id')
                ->where('lessons.tone_id', '=', $data['main_lyric']->tone_id)
                ->select('lessons.*', 'users.username')->where('lessons.status', '=', 'published')
                ->take(8)->orderBy('lessons.id', 'DESC')->get();

            // get tone
            $data['tone'] = $data['main_lyric']->tone()->first();
            if (!is_null($data['tone'])) {
                $data['lesson_tone'] = Lesson::join('users', 'users.id', '=', 'lessons.user_id')
                    ->where('lessons.tone_id', '=', $data['tone']->lesson_id)
                    ->select('lessons.*', 'users.username')->where('lessons.status', '=', 'published')
                    ->orderBy('lessons.id', 'DESC')->first();
            }
            //check current user activity
            $data['thanked'] = $data['favourited'] = 'login';
            if (Sentry::check()) {
                $uId = $this->data['u']->id;
                $data['thanked'] = $data['lyric']->thanks()->where('user_id', '=', $uId)->count() > 0 ? 'thank_active' : 'thank';
                $data['favourited'] = $data['lyric']->favourites()->where('user_id', '=', $uId)->count() > 0 ? 'favourite_active' : 'favourite';
            }

            // other version
            $data['versions'] = Lyric::join('users', 'users.id', '=', 'lyrics.user_id')
                ->where('status', '=', 'published')->where('lyrics.id', '!=', $id)
                ->where(function ($where) use ($parent_id) {
                    $where->where('lyrics.parent_id', '=', $parent_id)
                        ->orWhere('lyrics.id', '=', $parent_id);
                })
                ->select('lyrics.*', 'username')->get();

            //
            return View::make('frontend/lyrics/details', compact('data'));
        } else {
            return View::make('frontend/lyrics/details-fullscreen', compact('data'));
        }
    }

    public function getFullScreen($id, $slug)
    {
        $data['lyric'] = Lyric::join('users', 'users.id', '=', 'lyrics.user_id')
            ->where('lyrics.status', '=', 'published')->where('lyrics.id', '=', $id)
            ->select('lyrics.*', 'username')->first();
        if (is_null($data['lyric']))
            \App::abort(404);

        $data['guitar_tab'] = new GuitarTabs();
        $data['guitar_tab']->add_section('', $data['lyric']->content);

        return View::make('frontend/lyrics/details-fullscreen', compact('data'));
    }


    public function getCreate()
    {

        $myModel = new \MyModel();
        $data['topics'] = \Topic::returnArray();
        $data['categories'] = $myModel->listAllItemsToArray('Category', array('value' => 'id', 'display' => 'title'));
        $data['tones'] = $myModel->listAllItemsToArray('Tone', array('value' => 'id', 'display' => 'title'));
        $data['lyric'] = new Lyric();
        return View::make('frontend/lyrics/create', compact('data'));
    }

    public function postCreate()
    {
        $data = Input::get('data');
        $rules = array('title' => 'required', 'content' => 'required');
        $validation = Validator::make($data['Lyric'], $rules);
        if ($validation->fails())
            return Redirect::back()->withInput()->withErrors($validation);
        $data['Lyric']['user_id'] = Sentry::getUser()->id;
        $data['Lyric']['slug'] = Str::slug($data['Lyric']['title']);
        if (!Sentry::getUser()->hasAnyAccess(['lyric', 'lyric.approve'])) {
            $data['Lyric']['status'] = 'submitted';
        }
        $myModel = new MyModel();


        if (!empty($data['Singer']['id']))
            $data['Lyric']['singer_id'] = $data['Singer']['id'];
        else if (!empty($data['Singer']['name'])) {
            $singer_id = $myModel->saveItem('Singer', array('name' => $data['Singer']['name'], 'type' => 'singer'));
            $data['Lyric']['singer_id'] = $singer_id;
        }

        if (!empty($data['Musician']['id']))
            $data['Lyric']['musician_id'] = $data['Musician']['id'];
        else if (!empty($data['Musician']['name'])) {
            $musician_id = $myModel->saveItem('Singer', array('name' => $data['Musician']['name'], 'type' => 'musician'));
            $data['Lyric']['musician_id'] = $musician_id;
        }


        try {
            $lyric = $myModel->saveItem("Lyric", $data['Lyric'], array('return' => 'class'));
            if (isset($data['Topics'])) {
                $lyric->topics()->detach();
                $lyric->topics()->attach($data['Topics']);
            }


            if (isset($data['Tags']) && $data['Tags'] != '') {
                $tags = explode(',', $data['Tags']);
                foreach ($tags as $tag) {
                    $tag_id = \Tag::Check($tag);
                    $lyric->tags()->attach($tag_id);
                }
            }
        } catch (Exception $ex) {
            return Redirect::back()->withInput()->withErrors($ex);
        }

        if (!Sentry::getUser()->hasAnyAccess(['lyric', 'lyric.approve'])) {
            return Redirect::route('dang-hop-am')->with('success', 'Hợp âm của bạn sẽ được xét duyệt để hiển thị');
        } else
            return Redirect::route('chi-tiet-hop-am', array('id' => $lyric->id, 'name' => $data['Lyric']['slug']));
    }

    public function postAddVersion()
    {
        if (Request::ajax()) {
            $parent_id = Jinput::get('parent_id', '');
            $content = Input::get('content', '');
            $parent = Lyric::find($parent_id);
            $version = new Lyric();
            $version->title = $parent->title;
            $version->slug = $parent->slug;
            $version->user_id = Sentry::getUser()->id;
            $version->status = 'submitted';
            $version->content = $content;
            $version->parent_id = $parent_id;
            $version->tone_id = $parent->tone_id;
            $version->save();
        }
        return Response::json(array('success'));
    }
}